package cn.lijiajia3515.cairo.auth.framework.security.oauth2.server.authorization.client;

import cn.lijiajia3515.cairo.auth.domain.mongo.ClientMongo;
import cn.lijiajia3515.cairo.auth.domain.mongo.AuthMongoConstants;
import cn.lijiajia3515.cairo.auth.modules.client.Converter;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;

import java.util.Optional;

public class CairoRegisteredClientRepository implements RegisteredClientRepository {
    private final MongoTemplate mongoTemplate;

    public CairoRegisteredClientRepository(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public void save(RegisteredClient registeredClient) {

    }

    @Override
    public CairoRegisteredClient findById(String id) {
        Query query = Query.query(Criteria
                .where(ClientMongo.FIELD.ENABLED).is(true)
                .and(ClientMongo.FIELD.ID).is(id)
        );

        ClientMongo client = mongoTemplate.findOne(query, ClientMongo.class, AuthMongoConstants.Collection.CLIENT);

        return Optional.ofNullable(client).map(Converter::convert).orElse(null);
    }

    @Override
    public CairoRegisteredClient findByClientId(String clientId) {
        Query query = Query.query(Criteria
                .where(ClientMongo.FIELD.ENABLED).is(true)
                .and(ClientMongo.FIELD.CLIENT_ID).is(clientId)
        );

        ClientMongo client = mongoTemplate.findOne(query, ClientMongo.class, AuthMongoConstants.Collection.CLIENT);

        return Optional.ofNullable(client).map(Converter::convert).orElse(null);
    }

}
